﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Composite.Data;
using System.Transactions;
using Composite.Data.Transactions;
using LCA.Common.Extensions;
using LCA.Data;

public partial class Admin_LCAFlow_Controls_FlowEditor : System.Web.UI.UserControl
{
    public Guid? FlowId
    {
        get { return (Guid?)ViewState["FlowId"]; }
        set
        {
            ViewState["FlowId"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        
    }

    public void RefreshComponents()
    {
        using (DataConnection conn = new DataConnection())
        {
            // Bind Units
            var units = from u in conn.Get<LCA.Data.Unit>()
                        join uc in conn.Get<LCA.Data.UnitGroup>() on u.UnitGroup equals uc.Id
                        select new
                        {
                            Id = u.Id,
                            Name = uc.Name + " - " + u.Name
                        };
            units = units.OrderBy(x => x.Name);
            ddlUnit.DataSource = units;
            ddlUnit.DataBind();
            ddlUnit.Items.Insert(0, new ListItem("-- Please Select --", "NULL"));


            if (this.FlowId.HasValue)
            {
                var flowData = conn.Get<LCA.Data.Flow>().Where(x => x.Id == this.FlowId.Value).FirstOrDefault();

                txtName.Text = flowData.Name;
                rteDescription.Xhtml = flowData.Description;
                imgSelectorPicture.SelectedImageId = string.IsNullOrEmpty(flowData.Picture) ? null : flowData.Picture.Replace("MediaArchive:", "").ToGuid();
                ddlUnit.SelectedValue = flowData.Unit.HasValue ? flowData.Unit.Value.ToString() : "NULL";
                chkTechnoSphere.Checked = flowData.TechnoSphere;
                txtSource.Text = flowData.Source;

                litItemHeader.Text = string.Format("Edit a flow - {0} ({1})", flowData.Name, flowData.FlowId);


                // Debug only
                //var impacts = (from ff in conn.Get<LCA.Data.FlowFactor>()
                //               join f in conn.Get<LCA.Data.Flow>() on ff.Flow equals f.Id
                //               join fa in conn.Get<LCA.Data.Factor>() on ff.Factor equals fa.Id
                //               where f.Id == this.FlowId
                //               select new
                //               {
                //                   Id = ff.Id,
                //                   Name = fa.Name,
                //                   Emission = ff.Emission
                //               }).ToList();

                //grdImpactFactor.DataSource = impacts;
                //grdImpactFactor.DataBind();

                //var impacts = from flowfactor in conn.Get<LCA.Data.FlowFactor>() 
                //              join f in conn.Get<LCA.Data.Factor>() on flowfactor.Factor equals f.Id
                //              join ind in conn.Get<LCA.Data.Indicator>() on f.Indicator equals ind.Id
                //              join unit in conn.Get<LCA.Data.Unit>() on f.Unit equals unit.Id
                //              where flowfactor.Flow == this.FlowId
                //              orderby ind.Name descending
                //              select new
                //              {
                //                  Id = f.Id,
                //                  Name = f.Name,
                //                  Unit = unit.Name,
                //                  Amount = flowfactor.Amount.ToString()
                //              };

                //rptImpacts.DataSource = impacts;
                //rptImpacts.DataBind();
            }
            else
            {

                //var impacts = from f in conn.Get<LCA.Data.Factor>()
                //              join ind in conn.Get<LCA.Data.Indicator>() on f.Indicator equals ind.Id
                //              join unit in conn.Get<LCA.Data.Unit>() on f.Unit equals unit.Id
                //              orderby ind.Name descending
                //              select new
                //              {
                //                  Id = f.Id,
                //                  Name = f.Name,
                //                  Unit = unit.Name,
                //                  Amount = "-"
                //              };

                //rptImpacts.DataSource = impacts;
                //rptImpacts.DataBind();

                litItemHeader.Text = "Create a flow";
            }
        }
    }

    //protected void rptImpacts_ItemDataBound(object sender, RepeaterItemEventArgs e)
    //{
    //    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    //    {
    //        dynamic factor = e.Item.DataItem;
    //        Literal litImpactName = (Literal)e.Item.FindControl("litImpactName");
    //        litImpactName.Text = factor.Name;

    //        HiddenField hdnId = (HiddenField)e.Item.FindControl("hdnId");
    //        hdnId.Value = factor.Id.ToString();

    //        Label lblUnit = (Label)e.Item.FindControl("lblUnit");
    //        lblUnit.Text = factor.Unit;

    //        TextBox txtValue = (TextBox)e.Item.FindControl("txtValue");

    //        if (factor.Amount == "-")
    //            txtValue.Text = "0.0000";
    //        else
    //            txtValue.Text = factor.Amount.ToString(); 
            
    //    }
    //}

    public event EventHandler DataSaved;
    public event EventHandler Cancelled;

    protected virtual void OnDataSaved(EventArgs e)
    {
        if (DataSaved != null)
        {
            DataSaved(this, e);
        }
    }

    protected virtual void OnCancelled(EventArgs e)
    {
        if (Cancelled != null)
        {
            Cancelled(this, e);
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (SaveData())
            {
                OnDataSaved(new EventArgs());
            }
        }
    }

    private bool SaveData()
    {
        bool result = true;
        LCA.Data.Flow flow = null;

        using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
        {
            using (DataConnection connection = new DataConnection())
            {
                // Flow
                if (this.FlowId.HasValue)
                {
                    flow = connection.Get<LCA.Data.Flow>().Where(f => f.Id == this.FlowId).FirstOrDefault();
                }
                else
                {
                    flow = connection.CreateNew<LCA.Data.Flow>();
                    flow.FlowId = Sequences.FlowId.NextVal.Value;
                    flow.CreatedDate = DateTime.Now;
                }

                flow.Name = txtName.Text.Trim();
                flow.Description = rteDescription.Xhtml;
                flow.Picture = imgSelectorPicture.SelectedImageId == null ? null : ("MediaArchive:" + imgSelectorPicture.SelectedImageId.ToString());
                flow.Unit = ddlUnit.SelectedValue == "NULL" ? null : ddlUnit.SelectedValue.ToGuid();
                flow.TechnoSphere = chkTechnoSphere.Checked;
                flow.Source = txtSource.Text.Trim();

                if (this.FlowId.HasValue)
                    connection.Update(flow);
                else
                    connection.Add(flow);

                // Flow Factor
                //LCA.Data.FlowFactor flowFactor = null;
                //foreach(RepeaterItem item in rptImpacts.Items)
                //{
                //    HiddenField hdnId = (HiddenField) item.FindControl("hdnId");
                //    TextBox txtValue = (TextBox) item.FindControl("txtValue");

                //    if (this.FlowId.HasValue)
                //        flowFactor = connection.Get<LCA.Data.FlowFactor>().Where(f => f.Factor == hdnId.Value.ToGuid() && f.Flow == this.FlowId.Value).FirstOrDefault();
                //    else
                //    {
                //        flowFactor = connection.CreateNew<LCA.Data.FlowFactor>();
                //        LCA.Data.Factor factor = connection.Get<LCA.Data.Factor>().Where(i => i.Id == hdnId.Value.ToGuid()).FirstOrDefault();
                //        flowFactor.Factor = factor.Id;
                //        flowFactor.Flow = flow.Id;
                //    }

                //    flowFactor.Amount = txtValue.Text.Trim().ToDecimal().Value;

                //    if (this.FlowId.HasValue)
                //        connection.Update(flowFactor);
                //    else
                //        connection.Add(flowFactor);
                //}
                
            }

            transactionScope.Complete();
        }

        this.FlowId = flow.Id;


        return result;
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        OnCancelled(new EventArgs());
    }
}